package com.fqgj.xjd.user.service;

import com.fqgj.base.services.redis.RedisClient;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.MD5;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.xjd.user.client.UserBehaviorService;
import com.fqgj.xjd.user.client.enums.AppCodeEnum;
import com.fqgj.xjd.user.client.request.UserAccess;
import com.fqgj.xjd.user.client.request.UserProductCategory;
import com.fqgj.xjd.user.client.response.UserAccessInfo;
import com.fqgj.xjd.user.client.response.UserBehaviorRegister;
import com.fqgj.xjd.user.common.constants.UserProfileConsts;
import com.fqgj.xjd.user.common.utils.WeightRandomHandler;
import com.fqgj.xjd.user.config.ConfigUtil;
import com.fqgj.xjd.user.dao.*;
import com.fqgj.xjd.user.entity.*;
import com.fqgj.xjd.user.so.UserAccessToken;
import com.qianli.common.enums.AppEnum;
import com.robert.vesta.util.IdUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @ClassName:
 * @Description: 用户注册服务
 * @Author zhangxingyun
 * @Create 2017-07-21 09:37
 */
@Service
public class UserRegistService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserRegistService.class);
    @Autowired
    private UserAccessDao userAccessDao;
    @Autowired
    private UserBehaviorService userBehaviorService;
    @Autowired
    private UserBehaviorRegisterDao userBehaviorRegisterDao;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private UserCategoryDao userCategoryDao;
    @Autowired
    private UserAuthStatusDao userAuthStatusDao;
    @Autowired
    private UserLevelInfoDao userLevelInfoDao;

    @Autowired
    private UserOuterDataDao userOuterDataDao;

    public UserAccessInfo userRegister(UserAccess userAccess, String appCode) {
        String userCode = IdUtils.genId() + "";

        UserAccessEntity userAccessEntity = new UserAccessEntity();
        UserAccessToken userAccessToken = new UserAccessToken(userAccess.getUserCode());
        userAccessEntity.setUserCode(userAccess.getUserCode());
        if (userAccess.getPassword() != null && StringUtils.isNotEmpty(userAccess.getPassword().getPassword())) {
            userAccessEntity.setPassWord(userAccess.getPassword().getPassword());
        }
        userAccessEntity.setUserCode(userCode);
        userAccessEntity.setAppCode(appCode);
        userAccessEntity.setToken(userAccessToken.getToken());
        userAccessEntity.setExpireDate(userAccessToken.getExpireDate());
        userAccessEntity.setMobile(userAccess.getMobile().getMobile());
        userAccessEntity.setCreateDt(new Date());
        userAccessEntity.setPackageName(userAccess.getPackageName());
        userAccessEntity.setMd5Mobile(MD5.md5(userAccess.getMobile().getMobile()));


        //查询用户数据来源
        List<UserOuterDataEntity> userOuterDataEntities = userOuterDataDao.selectListByMobile(userAccess.getMobile().getMobile());
        if (!CollectionUtils.isEmpty(userOuterDataEntities)) {
            long minId = 0;
            UserOuterDataEntity rightSource = userOuterDataEntities.get(0);
            for (UserOuterDataEntity userOuterDataEntity : userOuterDataEntities) {
                if (userOuterDataEntity.getId() < minId) {
                    minId = userOuterDataEntity.getId();
                    rightSource = userOuterDataEntity;
                }
            }

            userAccessEntity.setBelongTo(rightSource.getSource());

        }

        userAccessDao.insert(userAccessEntity);
        userBehaviorService.addUserRegister(userCode, userAccess.getUserAppInfo());
        //boolean isNotOrganicChannel = configUtil.isNotOrganicChannel(userAccess.getUserAppInfo().getChannel());
        //用户绑定产品类目
        //String productCategory = bindProductCategory(userCode, userAccess.getUserProductCategoryList(), isNotOrganicChannel);
        //更新状态表
        UserAuthStatusEntity userAuthStatusEntity = new UserAuthStatusEntity();
        userAuthStatusEntity.setUserCode(userCode);
        userAuthStatusDao.insert(userAuthStatusEntity);
        //用户权益
        UserLevelInfoEntity userLevelInfoEntity = new UserLevelInfoEntity()
                .setLevelCode("0")
                .setUserCode(userCode)
                .setCreateDate(new Date())
                .setScore(0)
                .setTotalReward(0);
        userLevelInfoDao.insert(userLevelInfoEntity);
        return new UserAccessInfo(userCode, userAccessEntity.getToken(), userAccess.getMobile().getMobile(), "");
    }


    public UserAccessInfo register(UserAccess userAccess, AppCodeEnum appCodeEnum) {
        String userCode = IdUtils.genId() + "";
        UserAccessEntity userAccessEntity = new UserAccessEntity();
        UserAccessToken userAccessToken = new UserAccessToken(userAccess.getUserCode());
        userAccessEntity.setUserCode(userAccess.getUserCode());
        if (userAccess.getPassword() != null && StringUtils.isNotEmpty(userAccess.getPassword().getPassword())) {
            userAccessEntity.setPassWord(userAccess.getPassword().getPassword());
        }
        userAccessEntity.setUserCode(userCode);
        userAccessEntity.setAppCode(String.valueOf(AppEnum.JYD.getAppId()));
        userAccessEntity.setToken(userAccessToken.getToken());
        userAccessEntity.setExpireDate(userAccessToken.getExpireDate());
        userAccessEntity.setMobile(userAccess.getMobile().getMobile());
        userAccessEntity.setMd5Mobile(MD5.md5(userAccess.getMobile().getMobile()));
        userAccessEntity.setCreateDt(new Date());
        userAccessDao.insert(userAccessEntity);
//        userBehaviorService.addUserRegister(userCode, userAccess.getUserAppInfo());
        return new UserAccessInfo(userCode, userAccessEntity.getToken(), userAccess.getMobile().getMobile());
    }


    public UserBehaviorRegister getRegisterInfo(String userCode) {
        UserBehaviorRegisterEntity entity = userBehaviorRegisterDao.selectUserBehaviorRegisterByUserCodeAndAppCode(userCode);
        if (entity == null) {
            return null;
        }
        UserBehaviorRegister register = new UserBehaviorRegister();
        BeanUtils.copyProperties(entity, register);
        return register;
    }


    /**
     * 绑定产品类目
     */
    private String bindProductCategory(String userCode, List<UserProductCategory> userProductCategoryList, boolean isNotOrganicChannel) {
        //1. 遍历 产品类目列表  剔除达到阈值的产品类目
        Iterator<UserProductCategory> iterator = userProductCategoryList.iterator();
        while (iterator.hasNext()) {
            UserProductCategory userProductCategoryRO = iterator.next();
            String productCategoryName = userProductCategoryRO.getProductCategoryName();
            if (isNotOrganicChannel) {
                Long number = redisClient.getNumber(UserProfileConsts.DAILY_REGISTER_USER_LIMIT_NOT_ORGANIC, productCategoryName, DateUtil.getDate("yyyy-MM-dd"));
                LOGGER.info("用户绑定产品类目 userCode:{},productCategoryName:{},number:{},isNotOrganicChannel:{}", userCode, productCategoryName, number, isNotOrganicChannel);
                if (number != null && userProductCategoryRO.getDailyNotOrganicRegisterUserLimit() != null && number >= userProductCategoryRO.getDailyNotOrganicRegisterUserLimit()) {
                    iterator.remove();
                }
            } else {
                Long number = redisClient.getNumber(UserProfileConsts.DAILY_REGISTER_USER_LIMIT_ORGANIC, productCategoryName, DateUtil.getDate("yyyy-MM-dd"));
                LOGGER.info("用户绑定产品类目 userCode:{},productCategoryName:{},number:{},isNotOrganicChannel:{}", userCode, productCategoryName, number, isNotOrganicChannel);
                if (number != null && userProductCategoryRO.getDailyOrganicRegisterUserLimit() != null && number >= userProductCategoryRO.getDailyOrganicRegisterUserLimit()) {
                    iterator.remove();
                }
            }
        }
        //2. 其他的 筛选出一个
        List<String> productCategoryNameList = userProductCategoryList.stream().map(UserProductCategory::getProductCategoryName).collect(Collectors.toList());
        double[] weightArrays = new double[productCategoryNameList.size()];
        for (int i = 0; i < productCategoryNameList.size(); i++) {
            //权重一样
            weightArrays[i] = 1d;
        }
        int weightValue = WeightRandomHandler.getWeightRandom(weightArrays);
        String productCategoryName = productCategoryNameList.get(weightValue);
        //3. 设置 并 自增
        if (isNotOrganicChannel) {
            redisClient.incrBy(UserProfileConsts.DAILY_REGISTER_USER_LIMIT_NOT_ORGANIC, 1L, productCategoryName, DateUtil.getDate("yyyy-MM-dd"));
        } else {
            redisClient.incrBy(UserProfileConsts.DAILY_REGISTER_USER_LIMIT_ORGANIC, 1L, productCategoryName, DateUtil.getDate("yyyy-MM-dd"));
        }
        //4. 保存
        UserCategoryEntity userCategoryEntity = new UserCategoryEntity();
        userCategoryEntity.setUserCode(userCode);
        userCategoryEntity.setCategoryCode(productCategoryName);
        userCategoryDao.insert(userCategoryEntity);
        LOGGER.info("用户绑定产品类目 最终 userCode:{},productCategoryName:{}", userCode, productCategoryName);
        return productCategoryName;
    }
}
